﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace AyuBookmark.WinForm.Controls
{
    /// <summary>
    /// 标签编辑控件（支持多标签输入和自动补全）
    /// </summary>
    public class TagEditor : FlowLayoutPanel
    {
        private TextBox txtInput;
        private List<string> availableTags = new List<string>();
        private List<string> selectedTags = new List<string>();
        private AutoCompleteStringCollection autoCompleteSource = new AutoCompleteStringCollection();
        private int tagPadding = 6;
        private int tagMargin = 4;

        // 公共事件
        public event EventHandler<List<string>> TagsChanged;

        public TagEditor()
        {
            InitializeComponents();
            SetupAutoComplete();
        }

        private void InitializeComponents()
        {
            // 基础设置
            this.SuspendLayout();
            this.BackColor = Color.White;
            this.BorderStyle = BorderStyle.FixedSingle;
            this.AutoSize = true;
            this.WrapContents = true;
            this.Padding = new Padding(5);
            this.MinimumSize = new Size(200, 32);

            // 输入框
            this.txtInput = new TextBox();
            this.txtInput.BorderStyle = BorderStyle.None;
            this.txtInput.Margin = new Padding(3, 6, 3, 3);
            this.txtInput.Width = 100;
            this.txtInput.KeyDown += OnInputKeyDown;
            this.txtInput.LostFocus += OnInputLostFocus;
            this.txtInput.TextChanged += OnInputTextChanged;

            // 添加控件
            this.Controls.Add(this.txtInput);
            this.ResumeLayout(false);
        }

        private void SetupAutoComplete()
        {
            this.txtInput.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            this.txtInput.AutoCompleteSource = AutoCompleteSource.CustomSource;
            this.txtInput.AutoCompleteCustomSource = autoCompleteSource;
        }

        #region 公共方法
        /// <summary>
        /// 设置可选标签列表（用于自动补全）
        /// </summary>
        public void SetAvailableTags(IEnumerable<string> tags)
        {
            this.availableTags = tags.Distinct().ToList();
            this.autoCompleteSource.Clear();
            this.autoCompleteSource.AddRange(this.availableTags.ToArray());
        }

        /// <summary>
        /// 设置已选标签
        /// </summary>
        public void SetSelectedTags(IEnumerable<string> tags)
        {
            ClearTags();
            foreach (var tag in tags.Distinct())
            {
                AddTag(tag);
            }
        }

        /// <summary>
        /// 获取当前选中的标签
        /// </summary>
        public List<string> GetSelectedTags()
        {
            return new List<string>(this.selectedTags);
        }

        /// <summary>
        /// 清空所有已选标签
        /// </summary>
        public void ClearTags()
        {
            foreach (Control control in this.Controls.OfType<Label>().ToList())
            {
                this.Controls.Remove(control);
                control.Dispose();
            }
            this.selectedTags.Clear();
            this.Controls.Add(this.txtInput);
            this.txtInput.Text = "";
        }
        #endregion

        #region 私有方法
        private void AddTag(string tagText)
        {
            if (string.IsNullOrWhiteSpace(tagText) || selectedTags.Contains(tagText))
                return;

            // 创建标签控件
            var tagLabel = new Label();
            tagLabel.Text = tagText;
            tagLabel.BackColor = Color.LightGray;
            tagLabel.AutoSize = true;
            tagLabel.Padding = new Padding(tagPadding, 0, tagPadding, 0);
            tagLabel.Margin = new Padding(0, 0, tagMargin, tagMargin);
            tagLabel.Cursor = Cursors.Hand;

            // 添加关闭按钮
            var closeButton = new Label();
            closeButton.Text = "×";
            closeButton.Font = new Font(this.Font, FontStyle.Bold);
            closeButton.AutoSize = true;
            closeButton.Padding = new Padding(0, 0, tagPadding, 0);
            closeButton.Click += (s, e) => RemoveTag(tagLabel);

            // 容器面板
            var tagPanel = new FlowLayoutPanel();
            tagPanel.BackColor = Color.LightGray;
            tagPanel.Margin = new Padding(0, 0, tagMargin, tagMargin);
            tagPanel.WrapContents = false;
            tagPanel.AutoSize = true;
            tagPanel.Controls.Add(tagLabel);
            tagPanel.Controls.Add(closeButton);

            // 插入到输入框前面
            this.Controls.SetChildIndex(this.txtInput, this.Controls.Count - 1);
            this.Controls.Add(tagPanel);

            // 添加到选中列表
            this.selectedTags.Add(tagText);
            TagsChanged?.Invoke(this, this.selectedTags);
        }

        private void RemoveTag(Control tagControl)
        {
            this.selectedTags.Remove(((Label)tagControl.Controls[0]).Text);
            this.Controls.Remove(tagControl);
            tagControl.Dispose();
            TagsChanged?.Invoke(this, this.selectedTags);
        }

        private void CompleteCurrentInput()
        {
            var inputText = this.txtInput.Text.Trim();
            if (!string.IsNullOrEmpty(inputText))
            {
                AddTag(inputText);
                this.txtInput.Text = "";
            }
        }
        #endregion

        #region 事件处理
        private void OnInputKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                case Keys.Tab:
                    CompleteCurrentInput();
                    e.Handled = true;
                    break;

                case Keys.Back:
                    if (string.IsNullOrEmpty(this.txtInput.Text) && this.selectedTags.Count > 0)
                    {
                        // 删除最后一个标签
                        var lastTag = this.Controls[this.Controls.Count - 2] as FlowLayoutPanel;
                        RemoveTag(lastTag);
                    }
                    break;
            }
        }

        private void OnInputLostFocus(object sender, EventArgs e)
        {
            CompleteCurrentInput();
        }

        private void OnInputTextChanged(object sender, EventArgs e)
        {
            // 自动完成检测（输入逗号或分号时自动完成）
            if (this.txtInput.Text.EndsWith(",") || this.txtInput.Text.EndsWith(";"))
            {
                var text = this.txtInput.Text.Substring(0, this.txtInput.Text.Length - 1).Trim();
                if (!string.IsNullOrEmpty(text))
                {
                    this.txtInput.Text = "";
                    AddTag(text);
                }
            }
        }
        #endregion

        protected override void OnLayout(LayoutEventArgs levent)
        {
            base.OnLayout(levent);
            // 确保输入框宽度足够
            this.txtInput.Width = Math.Max(100, this.Width - 20);
        }
    }
}